package Problem20;

import java.util.Stack;

/**
 * 一道栈的运用题
 * 遇到左括号则全部入栈，遇到右括号则判断
 *          若栈为空，则 return false  否则继续判断
 *          若是和栈顶匹配，则栈顶出栈。若不匹配，return false
 * 最后再判断一下栈是否全清空，若没，则false ，否则true
 */

class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<Character>();
        for (int i = 0 ; i < s.length() ; i++){
            if (s.charAt(i) == '(' || s.charAt(i) == '['||s.charAt(i) == '{'){
                stack.push(s.charAt(i));
            }else {
                if (stack.empty()) return false;
                else if (matching( stack.peek() , s.charAt(i) )) stack.pop();
                else return false;
            }
        }
        return stack.empty() ? true : false;
    }
    public boolean matching (char a , char b){
        return ((a == '(' && b == ')') || (a == '[' && b == ']') || (a == '{' && b == '}') )? true:false;
    }
}